package com.jappit.runtracker.screens;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import com.jappit.runtracker.RunTracker;
import com.jappit.runtracker.data.DataManager;
import com.jappit.runtracker.data.RunSetHandler;
import com.jappit.runtracker.model.RunSet;
import com.jappit.runtracker.utils.AppUtils;
import com.jappit.runtracker.utils.FormatUtils;


public class RunListScreen extends List implements CommandListener, RunSetHandler
{
	Command newRun, deleteRun, exit;
	
	RunSet runs = null;
	
	public RunListScreen()
	{
		super("Your Runs", List.IMPLICIT);
		
		addCommand(newRun = new Command("New Run", Command.OK, 1));
		addCommand(exit = new Command("Exit", Command.EXIT, 1));
		deleteRun = new Command("Delete", Command.ITEM, 1);
		setCommandListener(this);
		
		refresh();
	}
	public void runSetModified()
	{
		refresh();
	}
	public void commandAction(Command c, Displayable d)
	{
		int index = runs.runsNum() - 1 - getSelectedIndex();
		
		if(c == exit)
		{
			AppUtils.getInstance().exit();
		}
		else if(c == List.SELECT_COMMAND)
		{
			AppUtils.getInstance().gotoScreen(new PastRunScreen(runs.getRun(index)));
		}
		else if(c == newRun)
		{
			AppUtils.getInstance().gotoScreen(new NewRunScreen(this));
		}
		else if(c == deleteRun && index >= 0 && runs.runsNum() > 0)
		{
			try
			{
				DataManager.getInstance().removeRun(runs.getRun(index));
				
				refresh();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	private void refresh()
	{
		this.deleteAll();
		
		runs = DataManager.getInstance().getRuns();
		
		for(int i = runs.runsNum() - 1; i >= 0; i--)
		{
			append(FormatUtils.formatDateTime(runs.getRun(i).getStartDate()), null);
		}
		if(runs.runsNum() > 0)
		{
			addCommand(deleteRun);
		}
		else
		{
			removeCommand(deleteRun);
		}
	}
}
